package com.yindian.cos.easy.security.authentication.token;

import com.yindian.cos.easy.security.exception.AuthenticationException;
import com.yindian.cos.easy.security.handler.AuthenticationFailureHandler;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 刷新token
 *
 * @author zhangchuanhao
 * @create 2018/11/21
 */
@Log4j2
@RestController
public class TokenController {

    @Autowired(required = false)
    private AbstractTokenFactory tokenFactory;

    @Autowired(required = false)
    private RefreshTokenNotify refreshTokenNotify;

    @Autowired(required = false)
    private AuthenticationFailureHandler authenticationFailureHandler;

    /**
     * 刷新token
     *
     * @param refreshToken
     * @return
     */
    @PostMapping("/token/refresh")
    public void refreshToken(@RequestHeader(name = "refresh_token") String refreshToken,
                             HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        try {
            Token token = tokenFactory.refresh(refreshToken);
            if (refreshTokenNotify == null) {
                refreshTokenNotify = new RefreshTokenNotify() {
                };
            }
            refreshTokenNotify.notify(request, response, token);
        } catch (AuthenticationException ex) {
            authenticationFailureHandler.handler(request, response, ex);
        }
    }

}
